//
//  AppDelegate.m
//  MingShi
//
//  Created by MJiao on 15/6/25.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "AppDelegate.h"
#import "MobClick.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "BPush.h"
#import "UserManager.h"
#import "IQKeyboardManager.h"
#import "PostRequestionViewController.h"
#import "QAViewController.h"
#import "DataSourceManager.h"
#import "NSString+Emoji.h"

@interface AppDelegate () <BPushDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [TencentOAuth HandleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [TencentOAuth HandleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.


//    NSString *emojiString = @"This is a cat ㊙😻 !";
//    emojiString = [emojiString stringByReplacingEmojiUnicodeWith:@""];
//    NSLog(@">>emojiString:%@",emojiString);

    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

#warning 上线 AppStore 时需要修改 pushMode
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"GpWYlyopdlZSpSKaNNmkSx33" pushMode:BPushModeProduction isDebug:YES];
//BPushModeDevelopment
    //BPushModeProduction
    //    [BPush setupChannel:launchOptions];

    // 设置 BPush 的回调
    [BPush setDelegate:self];

    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"百度推送:从消息启动:%@", userInfo);
        self.fromNotifyMsg = YES;
        [BPush handleNotification:userInfo];
    }


    //打开调试模式
//    [MobClick setLogEnabled:YES];

    //[MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    //
    [MobClick startWithAppkey:@"55a20a8467e58e6d94009afd" reportPolicy:REALTIME channelId:nil];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    double lastCheckTime = [userDefaults doubleForKey:@"lastCheckTime"];
    //数值是以 “秒” 为单位
    double now = [[NSDate date] timeIntervalSince1970];
    NSLog(@"now:%f", now);
//一天检查自动检查一次
    if (now - lastCheckTime > 3600 * 24) {
        /**
        *  检查更新(@2015-8-13 @铭师教育（贵阳补课） 要求T出掉改代码)
        */
        // [MobClick checkUpdate];
        [userDefaults setDouble:now forKey:@"lastCheckTime"];
    }


    [[IQKeyboardManager sharedManager] disableInViewControllerClass:[QAViewController class]];
    //[[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[PostRequestionViewController class]];

//    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:n];

    NSInteger applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber];
    //  NSLog(@"[UIApplication sharedApplication] applicationIconBadgeNumber]:%ld", applicationIconBadgeNumber);
    //获取
    [[DataSourceManager shareDataSourceManager] setNotifyCount:applicationIconBadgeNumber];

    return YES;
}

/**
*     app在后台运行时（backGround状态）：
*
*  @param application       <#application description#>
*  @param userInfo          <#userInfo description#>
*  @param completionHandler <#completionHandler description#>
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 打印到日志 textView 中
    NSLog(@"Baidu推送>>>>%@", [NSString stringWithFormat:@"backgroud : %@", userInfo]);
    if (!self.fromNotifyMsg && userInfo) {
        NSInteger plnum = [[userInfo objectForKey:@"plnum"] integerValue];
        [[DataSourceManager shareDataSourceManager] setNotifyCount:plnum];

        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
        [notificationCenter postNotificationName:@"processPushNotifyBadge" object:self userInfo:userInfo];
    }
    self.fromNotifyMsg = NO;

    completionHandler(UIBackgroundFetchResultNewData);

}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {

    [application registerForRemoteNotifications];


}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"Baidu推送 deviceToken:%@", deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannel];

    NSLog(@"Baidu推送 >>>%@", [NSString stringWithFormat:@"Register use deviceToken : %@", deviceToken]);


}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Baidu推送 DeviceToken 获取失败，原因：%@", error);

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];

    [notificationCenter postNotificationName:@"recvBaiduPushNotify" object:self userInfo:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // App 收到推送的通知
    [BPush handleNotification:userInfo];


    NSLog(@"Baidu推送 >>>>>%@", userInfo);
}

#pragma mark Push Delegate

- (void)onMethod:(NSString *)method response:(NSDictionary *)data {

    NSLog(@"Baidu推送>>>>>onMethod:%@", [NSString stringWithFormat:@"Method: %@\n%@", method, data]);
    @try {
        NSString *channelId = [data objectForKey:@"channel_id"];
        [[UserManager shareUserManager] setBdPushChannelId:channelId];

        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];

        [userInfo setObject:channelId forKey:@"bdPushChannelId"];

        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        [notificationCenter postNotificationName:@"recvBaiduPushNotify" object:self userInfo:userInfo];
    }
    @catch (NSException *exception) {
        NSLog(@"Baidu推送 Exception occurred: %@, %@", exception, [exception userInfo]);
    }

}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
